import 'dart:async';
import 'dart:isolate';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:psi/http/api_service.dart';
import 'package:psi/services/log_service.dart';
import 'package:psi/services/share_preference_service.dart';
import 'package:psi/services/user_logic.dart';
import 'package:psi/theme/app_colors.dart';
import 'package:psi/utils/oss_util.dart';

import 'app.dart';
import 'utils/utils.dart';

void main() {
  AppCatchError.run(() async {
    WidgetsFlutterBinding.ensureInitialized();
    await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitDown, DeviceOrientation.portraitUp]);
    await initServices();

    if (GetPlatform.isAndroid) {
      // 以下两行 设置android状态栏为透明的沉浸。写在组件渲染之后，是为了在渲染后进行set赋值，覆盖状态栏，写在渲染之前MaterialApp组件会覆盖掉这个值。
      SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        systemNavigationBarColor: bgColor,
        systemNavigationBarIconBrightness: Brightness.light,
        statusBarIconBrightness: Brightness.dark,
        statusBarBrightness: Brightness.light,
      );
      SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
    }
    runApp(const App());
  });
}

Future<void> initServices() async {
  /// 这里是你放get_storage、hive、shared_pref初始化的地方。
  /// 或者moor连接，或者其他什么异步的东西。

  if (!kIsWeb) {
    await Get.putAsync(() => LogService().init());
  }
  if (!Get.isRegistered<SharePreferenceService>()) {
    await Get.putAsync(() => SharePreferenceService().init());
  }
  if (!Get.isRegistered<ApiService>()) {
    Get.put(ApiService().init());
  }
  if (!Get.isRegistered<UserLogic>()) {
    Get.put(UserLogic(), permanent: true);
  }
  if (!Get.isRegistered<OssUtil>()) {
    Get.put(OssUtil(), permanent: true);
  }




}

abstract class AppCatchError {
  static run<T>(T Function() callback) {
    FlutterError.onError = (FlutterErrorDetails details) async {
      Utils.logD('发生FlutterError $details');
      if (kDebugMode || details.stack == null) {
        // 开发期间 print
        FlutterError.dumpErrorToConsole(details);
      } else {
        //线上环境
        Zone.current.handleUncaughtError(details.exception, details.stack!);
      }
    };

    if (!kIsWeb) {
      Isolate.current.addErrorListener(RawReceivePort((dynamic pair) {
        Utils.logD('发生Isolate错误 $pair');
        var isolateError = pair as List<dynamic>;
        var _error = isolateError.first;
        var _stackTrace = isolateError.last;
        Zone.current.handleUncaughtError(_error, _stackTrace);
      }).sendPort);
    }
    runZonedGuarded(() async {
      callback();
    }, (error, stack) => catchError(error, stack));


  }

  static void catchError(Object error, StackTrace stack) {
    Utils.logI('AppCatchError>>>>>>>>>>:');
    Utils.logE('APP发生未捕获异常', error: error, stackTrace: stack);
    Utils.logI('<<<<<<<<<<AppCatchError');
  }
}
